//
//  HJConversationCell.m
//  KaiChat
//
//  Created by xtjun on 2023/10/24.
//

#import "HJConversationCell.h"
#import "HJUnReadView.h"
#import "UIView+TUILayout.h"
#import "HJIM.h"


@interface HJConversationCell()<UIGestureRecognizerDelegate>

@property (nonatomic, strong) UILongPressGestureRecognizer *longPressGestureRecognizer;



@end


@implementation HJConversationCell {
    UIImageView *__weak _avatarImageView;
    UILabel * _nameLabel;
    UILabel *__weak _contentLabel;
    UILabel *__weak _timeLabel;
    UIImageView *__weak _disturbImageView;
    UIImageView *__weak _flagImageView;
    UIImageView *__weak _blacklistedTipImageView;
    HJUnReadView *__weak _unReadView;
    UIView *__weak _lineView;
    UIView *__weak _readPointView;
}

- (void)settingSubView {
    [super settingSubView];
    
    UIImageView *avatarImageView = [UIImageView addToView:self.contentView];
    avatarImageView.addCornerRadius(23);
    avatarImageView.contentMode = UIViewContentModeScaleAspectFill;
    
    UILabel *nameLabel = [UILabel lableWithSuperView:self.contentView font:UIFontMediumMake(14) color:UIColor.tj_333333Color title:nil textAlignment:NSTextAlignmentLeft];
    UILabel *timeLabel = [UILabel lableWithSuperView:self.contentView font:UIFontMake(12) color:UIColor.tj_BEBDCAColor title:nil textAlignment:NSTextAlignmentLeft];
    UILabel *contentLabel = [UILabel lableWithSuperView:self.contentView font:UIFontMake(13) color:UIColor.tj_868391Color title:nil textAlignment:NSTextAlignmentLeft];
    HJUnReadView *unReadView = [HJUnReadView addToView:self.contentView];
    unReadView.layer.backgroundColor = UIColor.tj_FF5100Color.CGColor;
    
    UIImageView *blacklistedTipImageView = [UIImageView addToView:self.contentView];
    blacklistedTipImageView.image = [UIImage imageNamed:@"msg_error"];
    blacklistedTipImageView.tj_size = CGSizeMake(blacklistedTipImageView.image.size.width, blacklistedTipImageView.image.size.height);
    blacklistedTipImageView.hidden = YES;
    
    UIImageView *flagImageView = [UIImageView addToView:self.contentView];
    flagImageView.tj_size = CGSizeMake(16, 16);
    flagImageView.hidden = YES;
    
    
    UIImageView *disturbImageView = [UIImageView addToView:self.contentView];
    disturbImageView.image = [UIImage imageNamed:@"mute_icon"];
    disturbImageView.tj_size = CGSizeMake(16, 16);
    disturbImageView.hidden = YES;
    
    UIView *lineView = [UIView addToView:self.contentView];
    lineView.backgroundColor = UIColor.whiteColor;
    
    UIView *readPointView = [UIView addToView:self.contentView];
    readPointView.tj_size = CGSizeMake(8, 8);
    readPointView.addCornerRadius(4);
    readPointView.hidden = YES;
    readPointView.backgroundColor = UIColor.redColor;
    
    _contentLabel = contentLabel;
    _avatarImageView = avatarImageView;
    _nameLabel = nameLabel;
    _timeLabel = timeLabel;
    _unReadView = unReadView;
    _lineView = lineView;
    _disturbImageView = disturbImageView;
    _readPointView = readPointView;
    _blacklistedTipImageView = blacklistedTipImageView;
    _flagImageView = flagImageView;
    
    UILongPressGestureRecognizer *longPressGestureRecognizer = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(longPress:)];
    longPressGestureRecognizer.delegate = self;
    _longPressGestureRecognizer = longPressGestureRecognizer;
    //    longPressGestureRecognizer.cancelsTouchesInView = NO;
    [self addGestureRecognizer:longPressGestureRecognizer];
}

- (BOOL)gestureRecognizerShouldBegin:(UIGestureRecognizer *)gestureRecognizer {
    if (gestureRecognizer == _longPressGestureRecognizer) {
        return YES;
    }
    return NO;
}

- (BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldRecognizeSimultaneouslyWithGestureRecognizer:(UIGestureRecognizer *)otherGestureRecognizer {
    if (gestureRecognizer == _longPressGestureRecognizer) {
        return YES;
    }
    return NO;
}

- (void)longPress:(UILongPressGestureRecognizer *)gesture {
    if (gesture.state == UIGestureRecognizerStateBegan) {
        if ([self.delegate respondsToSelector:@selector(tableViewCellLongPressGesture:)]) {
            [self.delegate tableViewCellLongPressGesture:self];
        }
    }
    
}


- (void)setHighlighted:(BOOL)highlighted {
    [super setHighlighted:highlighted];
    
    if (_model.isMute.boolValue) {
        _unReadView.layer.backgroundColor = UIColor.tj_BEBDCAColor.CGColor;
    } else {
        _unReadView.layer.backgroundColor = UIColor.tj_FF5100Color.CGColor;
    }
    
}

- (void)layoutSubviews {
    [super layoutSubviews];
    
    _avatarImageView.mm_width(46).mm_height(46).mm_left(leftRightMargin).mm__centerY(self.contentView.mm_centerY);
    
    _timeLabel.mm_sizeToFit().mm_right(leftRightMargin).mm_top(_avatarImageView.mm_y + 4);
    _nameLabel.mm_sizeToFit().mm_top(_avatarImageView.mm_y + 4).mm_left(_avatarImageView.mm_maxX + 10);
    
    CGFloat maxNameLabelW = self.mm_w - (_timeLabel.mm_w + 2 * leftRightMargin + _avatarImageView.mm_w + 10);
    if (_model.chatType == HJChatTypeGroup || _model.chatType == HJChatTypeOfficial) {
        maxNameLabelW = maxNameLabelW - 30;
    }
    
    _nameLabel.mm_w = MIN(maxNameLabelW, _nameLabel.mm_w);

    _contentLabel.mm_sizeToFit().mm_left(_nameLabel.mm_x).mm_bottom(_avatarImageView.mm_b + 3).mm_flexToRight( leftRightMargin * 2 + _unReadView.tj_width);
    
    _lineView.mm_left(leftRightMargin).mm_height(lineHeight).mm_top(self.contentView.mm_h - lineHeight).mm_width(self.contentView.mm_w - leftRightMargin * 2);
    _unReadView.tj_centerY = _contentLabel.tj_centerY;
    _unReadView.tj_x = self.tj_width - _unReadView.tj_width - leftRightMargin;
    
    _blacklistedTipImageView.tj_centerY = _unReadView.tj_centerY;
    _blacklistedTipImageView.tj_centerX = _unReadView.tj_centerX;
    
    _disturbImageView.tj_centerY = _nameLabel.tj_centerY;
    
    if (_model.chatType == HJChatTypeGroup || _model.chatType == HJChatTypeOfficial
        ) {
        _flagImageView.hidden = NO;
        _flagImageView.tj_x = _nameLabel.tj_x + _nameLabel.tj_width + 5;
        _disturbImageView.tj_x = _flagImageView.tj_MaxX + 5;
        _flagImageView.tj_centerY = _nameLabel.tj_centerY;
        _disturbImageView.tj_centerY = _nameLabel.tj_centerY;
    } else {
        _flagImageView.hidden = YES;
        _disturbImageView.tj_x = _nameLabel.tj_x + _nameLabel.tj_width + 5;
        _disturbImageView.tj_centerY = _nameLabel.tj_centerY;
    }
    
    _readPointView.tj_x = _avatarImageView.tj_MaxX - _readPointView.tj_width * 0.5;
    _readPointView.tj_y = _avatarImageView.tj_y - _readPointView.tj_height * 0.5 + 2;
}

- (void)setModel:(HJChatSessionModel *)model {
    _model = model;
        
    if (model.sessionNameAttributedstring) {
        _nameLabel.attributedText =  model.sessionNameAttributedstring;
    } else {
        _nameLabel.attributedText = nil;
        _nameLabel.text = model.sessionName;
    }
    
    
 if (isEmptyString(model.sessionAvatar)) {
        _avatarImageView.image = [UIImage imageNamed:defaultAvatarName];
    } else {
        [_avatarImageView tj_setImageWithURL:model.sessionAvatar.URL placeholderImage:[UIImage imageNamed:defaultAvatarName]];
    }
    
    if (model.chatType == HJChatTypeGroup) {
        _flagImageView.image = [UIImage imageNamed:@"conversation_group_icon"];
    } else if (model.chatType == HJChatTypeOfficial) {
        _flagImageView.image = [UIImage imageNamed:@"official_small"];
    } else {
        _flagImageView.image = nil;
    }
        
    if (model.chatType == HJChatTypeSingle) {
        
        if (model.systemMsgType == HJChatSystemMsgTypeApplyFridendAgree) {
            NSMutableAttributedString *attributedString = [[NSMutableAttributedString alloc] initWithString:[NSString stringWithFormat:@"%@ ", model.content] attributes:@{
                NSFontAttributeName: _contentLabel.font,
            }];
            NSTextAttachment *textAttachment = [[NSTextAttachment alloc] init];
            textAttachment.image = [UIImage imageNamed:@"hello"];
            textAttachment.bounds = CGRectMake(0, -3, 16, 16);
            NSAttributedString *iconAtt = [NSAttributedString attributedStringWithAttachment:textAttachment];
            [attributedString appendAttributedString:iconAtt];
            _contentLabel.attributedText = attributedString;
        } else {
            _contentLabel.text = [model getMessgetContent];
        }
        
    } else if (model.chatType == HJChatTypeGroup) {
        
        NSString *senderName = TJIM_isSelf(model.senderId) ? nil : model.senderName;
        BOOL isSelf = TJIM_isSelf(model.senderId);
        
        if ((!isSelf && model.hasNotice.boolValue && (model.timestamp.integerValue > model.readMessageTimestamp.integerValue))) {
            
            if (senderName) {
                _contentLabel.attributedText = [[NSString stringWithFormat:@"[Group Announcement] %@", [NSString stringWithFormat:@"%@: %@", senderName, [model getMessgetContent]]] attributedStringWithRangeString:@"[Group Announcement]" rangeColor:UIColorMake(0xE0421C) color:UIColor.tj_868391Color];
            } else {
                _contentLabel.attributedText = [[NSString stringWithFormat:@"[Group Announcement] %@", [NSString stringWithFormat:@"%@", [model getMessgetContent]]] attributedStringWithRangeString:@"[Group Announcement]" rangeColor:UIColorMake(0xE0421C) color:UIColor.tj_868391Color];
            }
            
        } else {
            if (_model.messageType == HJMessageTypeSystem || _model.messageType == HJMessageTypeOtherSystem) {
                _contentLabel.text = [model getMessgetContent];
            }  else {
                if (senderName && [model getMessgetContent]) {
                    _contentLabel.text = [NSString stringWithFormat:@"%@: %@", model.senderName, [model getMessgetContent]];
                } else {
                    _contentLabel.text = [model getMessgetContent];
                }
            }
        }
    } else {
        if (model.chatType == HJChatTypeOfficial) {
            _contentLabel.text = [model getMessgetContent];
        } else {
            _contentLabel.text = nil;
        }
        
    }
    

    if (model.isTop.boolValue) {
        self.backgroundColor = UIColor.tj_topCellBackgroundColor;
    } else {
        self.backgroundColor = UIColor.whiteColor;
    }
    
    
    if (model.messageType == HJMessageTypeSystem && [model.content isEqualToString:blacklistedTip]) {
        _unReadView.hidden = YES;
        _blacklistedTipImageView.hidden = NO;
    } else {
        _unReadView.hidden = NO;
        _blacklistedTipImageView.hidden = YES;
    }
    
    [_unReadView setNum:model.unReadCount.intValue];
    
    if (model.isMute.boolValue) {
        _disturbImageView.hidden = NO;
        _unReadView.layer.backgroundColor = UIColor.tj_BEBDCAColor.CGColor;
    } else {
        _disturbImageView.hidden = YES;
        _unReadView.layer.backgroundColor = UIColor.tj_FF5100Color.CGColor;
    }
    
    if (model.timestamp.integerValue > 0) {
        _timeLabel.text = [HJTools convertDateChatSessionListToString:[NSDate dateWithTimeIntervalSince1970:model.timestamp.integerValue / 1000]];
    } else {
        _timeLabel.text = nil;
    }
    
    [self setNeedsLayout];
    [self layoutIfNeeded];
}

- (void)dealloc {
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

@end
